import Vue from "vue";
import lodash from "lodash";
import store from '@/store';
import {api} from '../../service/scenario'
import tools from 'public/tools'

const modelState=store.state.admin.model;
const util= {
    Vue,
    ...tools,
    ...store.state.tools,
    store,
    api,
    modelState,
    deepCopy(data) {
        return JSON.parse(JSON.stringify(data))
    },
    getTypeListByModel: (model) => {
        if(!model){
            return [];
        }
        let typeRow = modelState.modelTree.filter(item => item.value.startsWith(model));
        if (!!typeRow) {
            return typeRow;
        } else {
            return [];
        }
    },
    getClassListByType: (type) => {
        let typeRow = modelState.modelTree.find(item => item.value === type);
        if (!!typeRow) {
            return typeRow.children;
        } else {
            return [];
        }
    },
    // 根据type和className获取values字段中所有key
    getKeyByTypeClass: (type,className) => {
        if(!type || !className){
            return [];
        }
        let valueObj = modelState.map.get(`${type},${className}`);
        let featureList = valueObj.featureList;
        let valueList = valueObj.valueList;
        let keyArr = [...featureList,...valueList];
        return keyArr;
    },
    getModel(type,className){
        return modelState.all.filter(item=>item.type===type&&item.className===className)
    },
    getCascader: (data, first, second ) => {
        let tree = [];
        data.map(item => {
            let index = tree.findIndex((m) => m.value === lodash.get(item, first));
            if (index === -1) {
                let obj = {
                    label: lodash.get(item, first),
                    value: lodash.get(item, first),
                    children: [
                        {
                            label:lodash.get(item, second),
                            labelRender: `${lodash.get(item, second)} \n ver.:${lodash.get(item, 'version')},pub.:${lodash.get(item, 'published')}`,
                            value: lodash.get(item, second),
                            id:lodash.get(item, 'id'),
                        },
                    ],
                };
                tree.push(obj);
            } else {
                tree[index].children.push({
                    label:lodash.get(item, second),
                    labelRender: `${lodash.get(item, second)} \n ver.:${lodash.get(item, 'version')},pub.:${lodash.get(item, 'published')}`,
                    value: lodash.get(item, second),
                    id:lodash.get(item, 'id'),
                });
            }
        });
        return tree;
    },
    getTree: (data, first, second) => {
        let tree = [];
        data.map(item => {
            let index = tree.findIndex((m) => m.value === lodash.get(item, first));
            if (index === -1) {
                let obj = {
                    title: lodash.get(item, first),
                    value: lodash.get(item, first),
                    id:lodash.get(item, 'id'),
                    expand: true,
                    children: [
                        {
                            title:lodash.get(item, second),
                            titleRender: `${lodash.get(item, second)} \n ver.:${lodash.get(item, 'version')},pub.:${lodash.get(item, 'published')}`,
                            value: [lodash.get(item, first), lodash.get(item, second)],
                            id:lodash.get(item, 'id'),
                            contextmenu: true,
                        },
                    ],
                };
                tree.push(obj);
            } else {
                tree[index].children.push({
                    title:lodash.get(item, second),
                    titleRender: `${lodash.get(item, second)} \n ver.:${lodash.get(item, 'version')},pub.:${lodash.get(item, 'published')}`,
                    value: [lodash.get(item, first), lodash.get(item, second)],
                    id:lodash.get(item, 'id'),
                    contextmenu: true,
                });
            }
        });
        return tree;
    },
    getFilter(filterMap, sign = '=='){
        let arr = [];
        if(!!filterMap){
            Object.keys(filterMap).map(key=>{
                let curItem = filterMap[key]
                let type = typeof curItem;
                let strWrap = (type ==='number' || type ==='boolean') ? "" : "'"

                if (curItem !== '' && curItem !== undefined && curItem !== null) {
                    if (sign === 'like' && strWrap) {
                        arr.push(`${key} like ${strWrap}%${curItem}%${strWrap}`)
                    } else {
                        arr.push(`${key} ${sign} ${strWrap}${curItem}${strWrap}`)
                    }
                }
            })
        };
        return arr.join(' && ');
    },
    formatTree(allList, rootList, setLabelValue, id='nodeId') {
        allList = allList.filter(item => item.nodeType !== 'root')
      
        if(rootList.length) {
            rootList = rootList.slice(0,1)
            rootList[0].isRoot = true
            getChild(rootList)
        }
      
        function getChild(list) {
          list.map(item => {
              let children = allList.filter(childItem => item[id] && (childItem.parentId === item[id]))
              if (setLabelValue) {
                children = children.map(cItem => {
                    return {
                        ...cItem,
                        title: cItem.nodeName,
                        value: cItem[id],
                    }
                })
                item.title = item.nodeName
                item.value = item[id]
              }
              children.length && getChild(children)
              item.children = children
          })
        }
        return rootList
    },
    // 构建表单字段信息
    buildFormField (item) {
        let field = {
            key: item.name,
            title: item.name,
        }
        switch (item.type) {
            case 'Double':
                field = {
                    ...field,
                    config: {
                      type: 'number',
                      min: 0,
                      max: 99999999,
                      precision: 2
                    }
                }
                break;
            case 'Integer':
                field = {
                    ...field,
                    config: {
                      type: 'number',
                      min: 0,
                      max: 99999999,
                      precision: 0
                    }
                }
                break;
            case 'Boolean':
                field = {
                    ...field,
                    config: {
                      type: 'check',
                    }
                }
                break;
            case 'DateTime':
                field = {
                    ...field,
                    config: {
                      type: 'datetime',
                    }
                }
                break;
            default:
                field = {
                    ...field,
                    config: {
                      type: 'text'
                    }
                }
                break;
        }
        return field;
    },
    // 动态生成当前实例对应的字段表
    /**
     * 当前记录
     */
    calcModelFields(modelList, curRecord) {
        let curModel = modelList.filter(item => item.className === curRecord.className)
        let modelFieldList=[]
        
        if (curModel && curModel.length) {
          let values = curRecord.values || {}
          let fieldObj = {}

          curModel[0].properties.forEach(item => {
            if (!fieldObj[item.name]) {
              curRecord.values[item.name] = values[item.name]
              fieldObj[item.name] = true  // 去重处理
              if (item.type === 'DateTime' && values[item.name]) {
                curRecord.values[item.name] = new Date(values[item.name])
              }
              modelFieldList.push(this.buildFormField(item))
            }
          })
        }
        return modelFieldList
    },
}
window.util=util;
export default util;